//
//  M_ProductDetailVC.swift
//  letuofu
//
//  Created by WH-JS on 2019/12/25.
//  Copyright © 2019 WH-JS. All rights reserved.
//

import UIKit
import MBProgressHUD
import WebKit
import MAMapKit
import AMapSearchKit
import SDWebImage
import JXPhotoBrowser

class M_ProductDetailVC: BaseViewControllerWithHeader,UIScrollViewDelegate,WKUIDelegate,WKNavigationDelegate,WKScriptMessageHandler,AMapSearchDelegate,MAMapViewDelegate {
    
    override func _drawScrollView()->ConstraintsScrollView{
        let s = ConstraintsScrollView()
        safeView.addSubview(s)
        s.snp.makeConstraints({ (make) in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(safeView.snp.top)
        })
        return s
    }
    
//    let headImgScrView = UIScrollView()
//    var headImgCurPage = 1
    let countLab = UILabel()
    let curLab = UILabel()
    lazy var headImageSlide : M_ProductDetailHeadImageSlide = { return M_ProductDetailHeadImageSlide(curLab: curLab) }()
    let desWeb = WKWebView()
    var observing = false
    var isLocationed = false
    let favBtn = BtmTitleBtn()
    let likeView = M_LikeView()
    
    let btmtoolView = UIView()
    var addBtn = Button()
    var buyBtn = Button()
    
    var productInfo : [String:Any?]
    
    let mapView = MAMapView()
    let search = AMapSearchAPI()
    let localLab = UILabel()
    let haveLab = UILabel()
    let wuhuoLab = UILabel()
    var curLocation : CLLocation?
    var shareImageUrlString = ""
    var shareTitle = ""
    var shareContent = ""
    var shareWebPageUrl = ""
    
//    var timer : Timer?
    var curHeadImg = 0
    let topBtn = Button()
//    //图片浏览器
//    let browser = JXPhotoBrowser()
    
//    func timerinvalidate() {
//        timer?.invalidate()
//        timer = nil
//        print("\(self)已销毁")
//    }
    
    init(info:[String:Any?]) {
        productInfo = info
        super.init()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        setupUI()
        getDataDetail(product: productInfo)
        getIsFav(productNo: productInfo.getString("productNo") ?? "", callback: { (data) in
            if data.getBool("isExist") ?? false,let collectID = data.getString("collectID") {
                self.favBtn.isSelected = true
                self.productInfo.updateValue(collectID, forKey: "collectID")
            }
            else {
                self.favBtn.isSelected = false
            }
        })
    }
    
    override func viewDidDisappear(_ animated: Bool) {
//        timerinvalidate()
        headImageSlide.stopTimer()
        scrollView.delegate = nil
//        headImgScrView.delegate = nil
        desWeb.uiDelegate = nil
        desWeb.navigationDelegate = nil
        mapView.delegate = nil
        search?.delegate = nil
        mapView.removeFromSuperview()
    }
    
    deinit {
//        timerinvalidate()
       headImageSlide.stopTimer()
       removeWebViewObserver()
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */
    
    func addCar(productNo: String) {
        MBProgressHUD.showOrIncrease()
        let params :[String:Any] = ["identityToken":LocalStorage.getString(forKey: USER_IDENTITYTOKEN) ?? "",
                                    "productNo":productNo]
        API.request(url: .M_AddCart, params: params) { (result) in
            MBProgressHUD.hideOrDecrease()
            if result.success {
                let popup = PopupBox(infoText: "成功加入购物车")
                popup.show(vc: UIViewController.topMostController() ?? self)
                
                let noT = NSNotification.Name(rawValue: CAR_CHANGE)
                let dic = ["key":"value"]
                NotificationCenter.default.post(name: noT, object: nil, userInfo:dic)
            }
            else {
                let popup = PopupBox(infoText: result.errMsg ?? "加入购物车失败")
                popup.show(vc: UIViewController.topMostController() ?? self)
            }
        }
    }
    
    func getIsFav(productNo :String,callback: @escaping ([String:Any?]) -> Void) {
        MBProgressHUD.showOrIncrease()
        let params :[String:Any] = ["identityToken":LocalStorage.getString(forKey: USER_IDENTITYTOKEN) ?? "",
                                    "productNo":productNo]
        API.request(url: .M_CheckProductCollectExist, params: params) { (result) in
            MBProgressHUD.hideOrDecrease()
            if result.success {
                if let dl = result.data?.getDictionary("data") {
                    callback(dl)
                }
            }
            else {
            }
        }
    }
    
    
    func getAddressIDByAddressName(provinceName :String,cityName :String,districtName :String,townName :String,callback: @escaping ([String:Any?]) -> Void) {
        MBProgressHUD.showOrIncrease()
        let province = provinceName.replacingOccurrences(of: "省", with: "")
        let params :[String:Any] = ["identityToken":LocalStorage.getString(forKey: USER_IDENTITYTOKEN) ?? "",
                                    "provinceName":province,
                                    "cityName":cityName,
                                    "districtName":districtName,
                                    "townName":townName]
        API.request(url: .M_GetAddressIDByAddressName, params: params) { (result) in
            MBProgressHUD.hideOrDecrease()
            if result.success {
                if let dl = result.data?.getDictionary("data") {
                    callback(dl)
                }
            }
            else {
            }
        }
    }
    
    func getProductStock(productNo :String,provinceCode :String, cityCode :String, districtCode :String, townCode :String, needStockNum :String = "1",callback: @escaping ([String:Any?]) -> Void) {
        MBProgressHUD.showOrIncrease()
        let params :[String:Any] = ["identityToken":LocalStorage.getString(forKey: USER_IDENTITYTOKEN) ?? "",
                                    "productNo":productNo,
                                    "provinceCode":provinceCode,
                                    "cityCode":cityCode,
                                    "districtCode":districtCode,
                                    "townCode":townCode,
                                    "needStockNum":needStockNum]
        API.request(url: .M_GetProductStock, params: params) { (result) in
            MBProgressHUD.hideOrDecrease()
            if result.success {
                if let dl = result.data?.getDictionary("data") {
                    callback(dl)
                }
            }
            else {
                callback([:])
            }
        }
    }
    
    func favAction(productNo: String,zoneCode: String,callback: @escaping () -> Void) {
        MBProgressHUD.showOrIncrease()
        let params :[String:Any] = ["identityToken":LocalStorage.getString(forKey: USER_IDENTITYTOKEN) ?? "",
                                    "productNo":productNo,
                                    "zoneCode":zoneCode]
        API.request(url: .M_AddCollectedProduct, params: params) { (result) in
            MBProgressHUD.hideOrDecrease()
            if result.success {
                callback()
            }
            else {
                let popup = PopupBox(infoText: result.errMsg ?? "收藏失败")
                popup.show(vc: UIViewController.topMostController() ?? self)
            }
        }
    }
    
    func delfavAction(collectID: String,callback: @escaping () -> Void) {
        MBProgressHUD.showOrIncrease()
        let params :[String:Any] = ["identityToken":LocalStorage.getString(forKey: USER_IDENTITYTOKEN) ?? "",
                                    "collectCode":collectID]
        API.request(url: .M_DeleteCollection, params: params) { (result) in
            MBProgressHUD.hideOrDecrease()
            if result.success {
                callback()
            }
            else {
                let popup = PopupBox(infoText: result.errMsg ?? "移除收藏失败")
                popup.show(vc: UIViewController.topMostController() ?? self)
            }
        }
    }
    
    func getDataDetail(product: [String:Any?]) {
        MBProgressHUD.showOrIncrease()
        let params :[String:Any] = ["identityToken":LocalStorage.getString(forKey: USER_IDENTITYTOKEN) ?? "",
                                    "productNo":product.getString("productNo") ?? ""]
        API.request(url: .M_GetProductDetail, params: params) { (result) in
            MBProgressHUD.hideOrDecrease()
            if result.success {
               if let dl = result.data?.getDictionary("data") {
                self.productInfo = self.productInfo.merging(dl, uniquingKeysWith: { (key1, key2) -> Any? in
                    return key2
                })
                   if dl.getString("zoneCode") == "105002" {
                       self.setupJDDetailUI()
                       return
                   }
                   else if dl.getString("zoneCode") == "105001" {
                       self.setupDetailUI()
                       return
                   }
                
               }

               let vc = DefultProVc()
               self.pushViewControllerWithAnimated(vc, animated: false)
            }
            else {
                let vc = DefultFieldVc()
                self.pushViewControllerWithAnimated(vc, animated: false)
            }

        }
    }
    
    
    func GetMallFreightIllustration(callback: @escaping ([String:Any?]) -> Void) {
        let params :[String:Any] = ["identityToken":LocalStorage.getString(forKey: USER_IDENTITYTOKEN) ?? "", "zoneCode": "105002"]
        API.request(url: .M_GetMallFreightIllustration, params: params) { (result) in
            if result.success {
               if let dl = result.data?.getDictionary("data") {
                   callback(dl)
               }
            }else{
            }
        }
    }
}

// MARK: UI
extension M_ProductDetailVC {
    func setupUI() {
        headView.backgroundColor = .clear
        backButton.setImage(UIImage.init(named: "fanghuiicon_73"), for: .normal)
        backButton.snp.remakeConstraints { (make) in
            make.centerX.equalTo(headView.snp.left).offset(15+33*0.5)
            make.centerY.equalTo(headView.snp.bottom).offset(-6-30*0.5)
        }
//        drawRightButton(imageName: "xiaoxi_76")
//        .addTarget(self, action: #selector(_xiaoxiButtonClick(button:)), for: .touchUpInside)
        let newsButton = drawRightButton(imageName: "xiaoxi_76")
        newsButton.addTarget(self, action: #selector(_xiaoxiButtonClick(button:)), for: .touchUpInside)
        UnreadPointForNewsButton(button: newsButton, pointRadius: 3.0,
                                 pointOffset: .init(x: -11.5, y: 13.5),  color: .xE0551B)

        drawRightButton(imageName: "fenxiang_75")
        .addTarget(self, action: #selector(_fenxiangButtonClick(button:)), for: .touchUpInside)
        
        drawRightButton(imageName: "sye_74")
        .addTarget(self, action: #selector(_homeButtonClick(button:)), for: .touchUpInside)
    }
    
    
    func setupDetailUI() {
        scrollView.bounces = false
        scrollView.clipsToBounds = false
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.showsVerticalScrollIndicator = false
        
        safeView.sendSubviewToBack(scrollView)
        scrollView.delegate = self
        scrollView.tag = 888
//        scrollView.addSubview(headImgScrView)
        scrollView.drawView(view: headImageSlide) { (make) in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(375)
        }
        headImageSlide.imageUrlPrefix = IMG_HOST_URL
        let imgListData = productInfo.getDictList("imgList") ?? []
        headImageSlide.setList(imgListData)
        headImageSlide.startTimer()
//        if let imgListData = productInfo.getDictList("imgList"),imgListData.count > 0 {
        if imgListData.count > 0 {
//            scrollView.drawView(view: headImgScrView) { (make) in
//                make.top.left.right.equalToSuperview()
//                make.height.equalTo(375)
//            }
//            headImgScrView.delegate = self
//            headImgScrView.clipsToBounds = false
//            headImgScrView.isPagingEnabled = true
//            headImgScrView.contentSize = CGSize(width: 375*imgListData.count, height: 295)
//            headImgScrView.showsVerticalScrollIndicator = false
//            headImgScrView.showsHorizontalScrollIndicator = false
//            headImgScrView.tag = 999
//            var i = 0
//            for item in imgListData {
//                let img = headImgScrView.drawImage(named: nil) { (make) in
//                    make.left.equalTo(i*375)
//                    make.top.equalToSuperview()
//                    make.width.equalTo(375)
//                    make.height.equalToSuperview()
//                }
//                if var urlstring = item.getString("imgUrl") {
//                    urlstring = (IMG_HOST_URL+urlstring).addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
//                    if self.shareImageUrlString.count == 0 {
//                        self.shareImageUrlString = urlstring
//                        if SDImageCache.shared.imageFromCache(forKey:urlstring) == nil {
//                            let urlimg = URL(string: urlstring)
//                            let downloader = SDWebImageDownloader.shared
//                            downloader.downloadImage(with: urlimg, options: [], progress: nil, completed: { (image,data,error,sec) in
//                                SDImageCache.shared.store(image, forKey: urlstring, completion: nil)
//                            })
//                        }
//                    }
//                    let url = URL(string: urlstring)
//                    img.sd_setImage(with:url)
//                    img.contentMode = .scaleAspectFit
//                }else{
//                    img.image = nil
//                }
//                i+=1
//            }
//            browser.numberOfItems = {i}
//            browser.reloadCellAtIndex = { context in
//                let browserCell = context.cell as? JXPhotoBrowserImageCell
//                let indexPath = IndexPath(item: context.index, section: 0)
//                if var urlstring = imgListData[indexPath.item].getString("imgUrl") {
//                    urlstring = (IMG_HOST_URL+urlstring).addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
//                    browserCell?.imageView.image = SDImageCache.shared.imageFromCache(forKey:urlstring)
//                }
//            }
//            headImgScrView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(headImgTap(tap:))))
//
//            if i == 0 {
//                headImgScrView.drawImage(named: "zanwu") { (make) in
//                    make.left.equalToSuperview()
//                    make.top.equalToSuperview()
//                    make.width.equalTo(375)
//                    make.height.equalToSuperview()
//                }
//            }

//            if i > 1 {
//                DispatchQueue.main.asyncAfter(deadline: .now() + 4) {
//                    self.timer=Timer.scheduledTimer(timeInterval:4, target:self, selector:#selector(self.functickDown), userInfo:nil, repeats:true)
//                    //开始计时器
//                    self.timer?.fire()
//                }
//            }
            
            safeView.drawLabel(label: countLab,text: anyToString(imgListData.count), fontSize: 12, textColor: .white) { (make) in
                make.bottom.equalTo(headImageSlide.snp.bottom).offset(-45.5)
                make.right.equalToSuperview().offset(-8.5)
            }

            safeView.drawLabel(label: curLab,text: anyToString(1)! + " /", fontSize: 14, textColor: .white) { (make) in
                make.bottom.equalTo(headImageSlide.snp.bottom).offset(-45.5)
                make.right.equalTo(countLab.snp.left).offset(-3)
            }

            let view = safeView.drawView { (make) in
                make.top.equalTo(curLab.snp.top).offset(-5)
                make.left.equalTo(curLab.snp.left).offset(-12)
                make.bottom.equalTo(curLab.snp.bottom).offset(5)
                make.right.equalTo(curLab.snp.right).offset(60)
            }
            view.backgroundColor = .init(white: 0, alpha: 0.2)
//            view.sendSubviewToBack(countLab)
            safeView.bringSubviewToFront(countLab)
            safeView.bringSubviewToFront(curLab)
            view.layer.cornerRadius = 14
            
            headImageSlide.activateTap()
        }
//        else {
//            scrollView.drawView(view: headImgScrView) { (make) in
//                make.top.left.right.equalToSuperview()
//                make.height.equalTo(375)
//            }
//            
//            headImgScrView.drawImage(named: "zanwu") { (make) in
//                make.left.equalToSuperview()
//                make.top.equalToSuperview()
//                make.width.equalTo(375)
//                make.height.equalToSuperview()
//            }
//        }
        
        let jifenIcon = scrollView.drawImage(named: "jifen_13") { (make) in
            make.left.equalToSuperview().offset(10)
//            make.top.equalTo(headImgScrView.snp.bottom).offset(17.5)
            make.top.equalTo(headImageSlide.snp.bottom).offset(17.5)
        }
        
        if let id = productInfo["productNo"] {
            self.shareWebPageUrl = "https://mcw.51camel.com/Product/ProductDetail?productID=\(id ?? "")"
        }
        self.shareTitle = productInfo.getString("productName") ?? ""
        self.shareContent = productInfo.getString("productShortDes") ?? ""
        
        var lab = scrollView.drawLabel(text: anyToString(productInfo["employeeCentPrice"] ?? productInfo["marketCentPricing"] ?? "     "), fontSize: 24, fontWeight: .medium, textColor: .xFC4C02) { (make) in
            make.left.equalToSuperview().offset(26)
            make.bottom.equalTo(jifenIcon).offset(7)
        }
        
//        scrollView.drawLabel(text: "原价" + (anyToString(productInfo["marketCentPricing"] ?? "") ?? "") + (productInfo.getString("centUnitName") ?? ""), fontSize: 11, fontWeight: .regular, textColor: .x999999) { (make) in
//            make.left.equalTo(lab.snp.right).offset(11.5)
//            make.bottom.equalTo(lab.snp.bottom).offset(-2)
//        }
        
//        lab = scrollView.drawLabel(text: "京东专区商品价格随时变动，请以订单结算为准！", fontSize: 11, fontWeight: .regular, textColor: .x999999) { (make) in
//            make.left.equalToSuperview().offset(10)
//            make.top.equalTo(lab.snp.bottom).offset(10)
//        }
        
        scrollView.drawButton(button: favBtn,imageNamed: "shoucang_78") { (make) in
            make.right.equalToSuperview().offset(-13.5)
//            make.top.equalTo(headImgScrView.snp.bottom).offset(7.5)
            make.top.equalTo(headImageSlide.snp.bottom).offset(7.5)
        }
        favBtn.setImage(UIImage.init(named: "yishoucang_77"), for: .selected)
        favBtn.addTarget(self, action: #selector(_favButtonClick(button:)), for: .touchUpInside)
        
        lab = scrollView.drawLabel(text: productInfo.getString("productName"), fontSize: 15, textColor: .x333333) { (make) in
//            make.top.equalTo(headImgScrView.snp.bottom).offset(70-22-3)
            make.top.equalTo(headImageSlide.snp.bottom).offset(70-22-3)
            make.left.equalTo(jifenIcon)
            make.right.equalToSuperview().offset(-25)
        }
        lab.minimumScaleFactor = 14
        lab.numberOfLines = 0
        
        lab = scrollView.drawLabel(text: "商品编号：" + (productInfo.getString("productNo") ?? ""), fontSize: 11, textColor: .x999999) { (make) in
            make.top.equalTo(lab.snp.bottom).offset(20-7)
            make.left.equalToSuperview().offset(10)
        }
        
        lab = scrollView.drawLabel(text: "浏览量：" + (anyToString(productInfo.getInt("viewNum")) ?? "") + " 兑换量：" + (anyToString(productInfo.getInt("sellNum")) ?? ""),
                                   fontSize: 11, textColor: .x999999) { (make) in
            make.centerY.equalTo(lab)
            make.right.equalToSuperview().offset(-10)
        }
        
        //画横线
        let line = scrollView.drawView { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(lab.snp.bottom).offset(14)
            make.height.equalTo(10)
        }
        line.backgroundColor = .xF2F2F2
        
        scrollView.drawLabel(text: "商品详情", fontSize: 15, textColor: .x333333) { (make) in
            make.top.equalTo(line.snp.bottom).offset(20)
            make.left.equalToSuperview().offset(10)
        }
        
        scrollView.drawView(view: desWeb) { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(line.snp.bottom).offset(50)
            make.height.equalTo(200)
        }
        desWeb.uiDelegate = self
        desWeb.navigationDelegate = self
        var detail = productInfo.getString("productDescription") ?? ""
        detail = "<html><head><style>img{width:100% !important;}p{margin:0 !important}</style> " +
        "<body style='margin:0;padding:0'>" + detail + "</body></head></html>"
        desWeb.loadHTMLString(detail, baseURL: nil)
        desWeb.scrollView.isScrollEnabled = false
        
        scrollView.drawView(view: likeView) { (make) in
            make.top.equalTo(desWeb.snp.bottom)
            make.left.right.equalToSuperview()
            make.height.equalTo(52)
        }
        
        likeView.getDataList(zoneCode: "105001", pageIndex: 1, pageSize: 10, callback: { (count) in
              var rownum = Double(count)/2
              rownum = ceil(rownum)
              self.likeView.snp.remakeConstraints { (make) in
              make.top.equalTo(self.desWeb.snp.bottom)
              make.left.right.equalToSuperview()
              make.height.equalTo(rownum*260+52+20)
            }
        })
        likeView.callselBlock { (info) in
            let vc = M_ProductDetailVC(info: info)
            self.pushViewController(vc)
        }
        scrollView.bottomEqualTo(likeView, offset: 50)
        ///底部工具条部分
        let btm = 50
        safeView.drawView(view: btmtoolView) { (make) in
            make.bottom.equalToSuperview().offset(btm)
            make.left.right.equalToSuperview()
            make.height.equalTo(100)
        }
        btmtoolView.backgroundColor = .white
        let kefuBtn = BtmTitleBtn()
        btmtoolView.drawButton(button: kefuBtn,imageNamed: "xiangqingkefu_82") { (make) in
            make.top.equalToSuperview().offset(8)
            make.left.equalToSuperview().offset(20)
        }
        kefuBtn.hitEdgInsets = .init(top: -20, left: -20, bottom: -20, right: -20)
        kefuBtn.btmLab.text = "客服"
        kefuBtn.addTarget(self, action: #selector(_kefuButtonClick(button:)), for: .touchUpInside)
        
        let carBtn = BtmTitleBtn()
        btmtoolView.drawButton(button: carBtn,imageNamed: "xiangqinggwuche_83") { (make) in
            make.top.equalToSuperview().offset(8)
            make.left.equalToSuperview().offset(74)
        }
        carBtn.hitEdgInsets = .init(top: -20, left: -20, bottom: -20, right: -20)
        carBtn.btmLab.text = "购物车"
        carBtn.addTarget(self, action: #selector(_gouwucheButtonClick(button:)), for: .touchUpInside)
        
        addBtn = btmtoolView.drawButton(title: "加入购物车", titleColor: .white, fontSize: 14) { (make) in
            make.left.equalToSuperview().offset(135)
            make.top.equalToSuperview().offset(7.5)
            make.height.equalTo(35)
            make.width.equalTo(110)
        }
        addBtn.backgroundColor = .xFFC000
        addBtn.layer.cornerRadius = 17.5
        addBtn.addTarget(self, action: #selector(_addButtonClick(button:)), for: .touchUpInside)
        
        buyBtn = btmtoolView.drawButton(title: "立即兑换", titleColor: .white, fontSize: 14) { (make) in
            make.right.equalToSuperview().offset(-10)
            make.top.equalToSuperview().offset(7.5)
            make.height.equalTo(35)
            make.width.equalTo(110)
        }
        buyBtn.backgroundColor = .xFC4C02
        buyBtn.layer.cornerRadius = 17.5
        buyBtn.addTarget(self, action: #selector(_buyButtonClick(button:)), for: .touchUpInside)
        
        safeView.drawButton(button: topBtn,imageNamed: "jiantou", { (make) in
            make.bottom.equalTo(btmtoolView.snp.top).offset(-15)
            make.right.equalToSuperview().offset(-15)
            make.width.height.equalTo(45)
        })
        topBtn.isHidden = true
        topBtn.backgroundColor = .white
        topBtn.layer.cornerRadius = 22.5
        topBtn.addTarget(self, action: #selector(_topButtonClick(button:)), for: .touchUpInside)
        
        //禁止长按,放缩
        var javascript = "document.documentElement.style.webkitTouchCallout='none';"//禁止长按
        javascript += "document.documentElement.style.webkitUserSelect='none';"//禁止选择
        var noneSelectScript = WKUserScript(source: javascript, injectionTime: WKUserScriptInjectionTime.atDocumentEnd, forMainFrameOnly: true)
        desWeb.configuration.userContentController.addUserScript(noneSelectScript)
        javascript = "var script = document.createElement('meta');script.name = 'viewport';script.content=\"width=device-width, user-scalable=no\";document.getElementsByTagName('head')[0].appendChild(script);"//禁止缩放
        noneSelectScript = WKUserScript(source: javascript, injectionTime: WKUserScriptInjectionTime.atDocumentEnd, forMainFrameOnly: false)
        desWeb.configuration.userContentController.addUserScript(noneSelectScript)
    }
    
    func setupJDDetailUI() {
        safeView.addSubview(mapView)
        mapView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(headView.snp.bottom)
            make.height.equalTo(0)
        }
        mapView.delegate = self
        mapView.showsUserLocation = true
        mapView.userTrackingMode = .none
        mapView.zoomLevel = 14
        
        scrollView.bounces = false
        scrollView.clipsToBounds = false
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.showsVerticalScrollIndicator = false
        
        safeView.sendSubviewToBack(scrollView)
        scrollView.delegate = self
        scrollView.tag = 888
//        scrollView.addSubview(headImgScrView)
        scrollView.drawView(view: headImageSlide) { (make) in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(375)
        }
        
        headImageSlide.imageUrlPrefix = JDIMG_HOST_URL
        let imgListData = productInfo.getDictList("imgList") ?? []
        headImageSlide.setList(imgListData)
        headImageSlide.startTimer()

//        if let imgListData = productInfo.getDictList("imgList"),imgListData.count > 0 {
        if imgListData.count > 0 {
//            scrollView.drawView(view: headImgScrView) { (make) in
//                make.top.left.right.equalToSuperview()
//                make.height.equalTo(375)
//            }
//            headImgScrView.delegate = self
//            headImgScrView.clipsToBounds = false
//            headImgScrView.isPagingEnabled = true
//            headImgScrView.contentSize = CGSize(width: 375*imgListData.count, height: 295)
//            headImgScrView.showsVerticalScrollIndicator = false
//            headImgScrView.showsHorizontalScrollIndicator = false
//            headImgScrView.tag = 999
//            var i = 0
//            for item in imgListData {
//                let img = headImgScrView.drawImage(named: nil) { (make) in
//                    make.left.equalTo(i*375)
//                    make.top.equalToSuperview()
//                    make.width.equalTo(375)
//                    make.height.equalToSuperview()
//                }
//                if var urlstring = item.getString("imgUrl") {
//                    urlstring = JDIMG_HOST_URL+urlstring
//                    if self.shareImageUrlString.count == 0 {
//                        self.shareImageUrlString = urlstring
//                        if SDImageCache.shared.imageFromCache(forKey:urlstring) == nil {
//                            let urlimg = URL(string: urlstring)
//                            let downloader = SDWebImageDownloader.shared
//                            downloader.downloadImage(with: urlimg, options: [], progress: nil, completed: { (image,data,error,sec) in
//                                SDImageCache.shared.store(image, forKey: urlstring, completion: nil)
//                            })
//                        }
//                    }
//                    let url = URL(string: urlstring)
//                    img.sd_setImage(with:url)
//                    img.contentMode = .scaleAspectFit
//                }else{
//                    img.image = nil
//                }
//                i+=1
//            }
//            browser.numberOfItems = {i}
//            browser.reloadCellAtIndex = { context in
//                let browserCell = context.cell as? JXPhotoBrowserImageCell
//                let indexPath = IndexPath(item: context.index, section: 0)
//                if var urlstring = imgListData[indexPath.item].getString("imgUrl") {
//                    urlstring = JDIMG_HOST_URL+urlstring
//                    browserCell?.imageView.image = SDImageCache.shared.imageFromCache(forKey:urlstring)
//                }
//            }
//            headImgScrView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(headImgTap(tap:))))
            
//            if i == 0 {
//                headImgScrView.drawImage(named: "zanwu") { (make) in
//                    make.left.equalToSuperview()
//                    make.top.equalToSuperview()
//                    make.width.equalTo(375)
//                    make.height.equalToSuperview()
//                }
//            }

//            if i > 1 {
//                DispatchQueue.main.asyncAfter(deadline: .now() + 4) {
//                    self.timer=Timer.scheduledTimer(timeInterval:4, target:self, selector:#selector(self.functickDown), userInfo:nil, repeats:true)
//                    //开始计时器
//                    self.timer?.fire()
//                }
//            }

//            scrollView.drawImage(named: "jingdongpeisong_66") { (make) in
//                make.top.equalToSuperview().offset(44.5)
//                make.right.equalToSuperview()
//            }

            let jingdongBox = M_ProductJINGDONGBox()
            scrollView.drawView(view: jingdongBox) { (make) in
                make.right.equalToSuperview()
                make.top.equalToSuperview().offset(46)
            }

            safeView.drawLabel(label: countLab,text: anyToString(imgListData.count), fontSize: 12, textColor: .white) { (make) in
                make.bottom.equalTo(headImageSlide.snp.bottom).offset(-45.5)
                make.right.equalToSuperview().offset(-8.5)
            }

            safeView.drawLabel(label: curLab,text: anyToString(1)! + " /", fontSize: 14, textColor: .white) { (make) in
                make.bottom.equalTo(headImageSlide.snp.bottom).offset(-45.5)
                make.right.equalTo(countLab.snp.left).offset(-3)
            }

            let view = safeView.drawView { (make) in
                make.top.equalTo(curLab.snp.top).offset(-5)
                make.left.equalTo(curLab.snp.left).offset(-12)
                make.bottom.equalTo(curLab.snp.bottom).offset(5)
                make.right.equalTo(curLab.snp.right).offset(60)
            }
            view.backgroundColor = .init(white: 0, alpha: 0.2)
            safeView.bringSubviewToFront(countLab)
            safeView.bringSubviewToFront(curLab)
//            view.sendSubviewToBack(countLab)
            view.layer.cornerRadius = 14
            
            headImageSlide.activateTap()
        }
//        else {
//            scrollView.drawView(view: headImgScrView) { (make) in
//                make.top.left.right.equalToSuperview()
//                make.height.equalTo(375)
//            }
//
//            headImgScrView.drawImage(named: "zanwu") { (make) in
//                make.left.equalToSuperview()
//                make.top.equalToSuperview()
//                make.width.equalTo(375)
//                make.height.equalToSuperview()
//            }
//        }
        
        let jifenIcon = scrollView.drawImage(named: "jifen_13") { (make) in
            make.left.equalToSuperview().offset(10)
//            make.top.equalTo(headImgScrView.snp.bottom).offset(17.5)
            make.top.equalTo(headImageSlide.snp.bottom).offset(17.5)
        }
        
        if let id = productInfo["productNo"] {
            self.shareWebPageUrl = "https://mcw.51camel.com/Product/JDProductDetail?productID=\(id ?? "")"
        }
        self.shareTitle = productInfo.getString("productName") ?? ""
        self.shareContent = productInfo.getString("productShortDes") ?? ""
        
        var lab = scrollView.drawLabel(text: anyToString(productInfo["employeeCentPrice"] ?? productInfo["marketCentPricing"] ?? "     "), fontSize: 24, fontWeight: .medium, textColor: .xFC4C02) { (make) in
            make.left.equalToSuperview().offset(26)
            make.bottom.equalTo(jifenIcon).offset(7)
        }
        
        let dl = LocalStorage.getDic(forKey: DEFULT_MALL)
        scrollView.drawLabel(text: "市场价 " + (anyToString(productInfo["marketCentPricing"] ?? "") ?? "") + (dl?.getString("centName") ?? ""), fontSize: 11, fontWeight: .regular, textColor: .x999999) { (make) in
            make.left.equalTo(lab.snp.right).offset(11.5)
            make.bottom.equalTo(jifenIcon).offset(2)
        }
        
        lab = scrollView.drawLabel(text: "京东专区商品价格随时变动，请以订单结算为准！", fontSize: 11, fontWeight: .regular, textColor: .x999999) { (make) in
            make.left.equalTo(jifenIcon)
            make.top.equalTo(jifenIcon.snp.bottom).offset(11)
        }
        
        scrollView.drawButton(button: favBtn,imageNamed: "shoucang_78") { (make) in
            make.right.equalToSuperview().offset(-13.5)
//            make.top.equalTo(headImgScrView.snp.bottom).offset(7.5)
            make.top.equalTo(headImageSlide.snp.bottom).offset(7.5)
        }
        favBtn.setImage(UIImage.init(named: "yishoucang_77"), for: .selected)
        favBtn.addTarget(self, action: #selector(_favButtonClick(button:)), for: .touchUpInside)
        favBtn.isHidden = true
        
        lab = scrollView.drawLabel(text: productInfo.getString("productName"), fontSize: 15,fontWeight:.medium, textColor: .x333333) { (make) in
//            make.top.equalTo(headImgScrView.snp.bottom).offset(70-3)
            make.top.equalTo(headImageSlide.snp.bottom).offset(70-3)
            make.left.equalTo(jifenIcon)
            make.right.equalToSuperview().offset(-25)
        }
        lab.minimumScaleFactor = 14
        lab.numberOfLines = 0
        
        lab = scrollView.drawLabel(text: "商品编号：" + (productInfo.getString("productNo") ?? ""), fontSize: 11, textColor: .x999999) { (make) in
            make.top.equalTo(lab.snp.bottom).offset(20-7)
            make.left.equalToSuperview().offset(10)
        }
        
        lab = scrollView.drawLabel(text: "浏览量：" + (anyToString(productInfo.getInt("viewNum")) ?? "") + " 兑换量：" + (anyToString(productInfo.getInt("sellNum")) ?? ""),
                                   fontSize: 11, textColor: .x999999) { (make) in
            make.centerY.equalTo(lab)
            make.right.equalToSuperview().offset(-10)
        }
        
        //画横线
        var line = scrollView.drawView { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(lab.snp.bottom).offset(14)
            make.height.equalTo(10)
        }
        line.backgroundColor = .xF2F2F2
        
        ///运费模块（京东特有）
        let bgview = scrollView.drawView { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(line.snp.bottom)
            make.height.equalTo(75)
        }
        bgview.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(jdADViewTap(tap:))))
        
        bgview.drawLabel(text: "送至", fontSize: 15, textColor: .x999999) { (make) in
            make.left.equalToSuperview().offset(10)
            make.top.equalToSuperview().offset(20)
        }
        
        bgview.drawLabel(label: localLab,text: "无法获取当前位置", fontSize: 15, textColor: .x333333) { (make) in
            make.left.equalToSuperview().offset(46)
            make.top.equalToSuperview().offset(20)
//            make.width.equalTo(270)
        }
        localLab.minimumScaleFactor = 0.7
        localLab.adjustsFontSizeToFitWidth = true
        localLab.preferredMaxLayoutWidth = 275
        
        bgview.drawImage(named: "bfuhe_80") { (make) in
            make.left.equalToSuperview().offset(10)
            make.bottom.equalToSuperview().offset(-15)
        }
        
        let lab_jichu = bgview.drawLabel(text: "108.00美晨积分 免京东运费", fontSize: 12, textColor: .x999999) { (make) in
            make.left.equalToSuperview().offset(25)
            make.bottom.equalToSuperview().offset(-13)
        }
        
        GetMallFreightIllustration(callback: { (data) in
            let fuwuStr = data.getString("jdFreightIllustration") ?? ""
            lab_jichu.text = fuwuStr
        })
        
        let jichuBtn = bgview.drawButton(title: "", titleColor: .white, fontSize: 14) { (make) in
            make.center.equalTo(lab_jichu)
            make.height.equalTo(35)
            make.width.equalTo(265)
        }
        jichuBtn.addTarget(self, action: #selector(_jichuClick(button:)), for: .touchUpInside)
        ///
        
        //画横线
        line = scrollView.drawView { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(bgview.snp.bottom)
            make.height.equalTo(10)
        }
        line.backgroundColor = .xF2F2F2
        
        scrollView.drawLabel(text: "商品详情", fontSize: 15, textColor: .x333333) { (make) in
            make.top.equalTo(line.snp.bottom).offset(20)
            make.left.equalToSuperview().offset(10)
        }
        
        scrollView.drawView(view: desWeb) { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(line.snp.bottom).offset(50)
            make.height.equalTo(200)
        }
        desWeb.uiDelegate = self
        desWeb.navigationDelegate = self
        var htmlstr = productInfo.getString("productDescription") ?? ""
        htmlstr = htmlstr.replacingOccurrences(of: "=\"//", with: "=\"https://")
        htmlstr = htmlstr.replacingOccurrences(of: "='//", with: "='https://")
        desWeb.loadHTMLString(htmlstr, baseURL: nil)
        desWeb.scrollView.isScrollEnabled = false
        
        scrollView.drawView(view: likeView) { (make) in
            make.top.equalTo(desWeb.snp.bottom)
            make.left.right.equalToSuperview()
            make.height.equalTo(52)
        }
        
        likeView.getDataList(zoneCode: "105002", pageIndex: 1, pageSize: 10, callback: { (count) in
              var rownum = Double(count)/2
              rownum = ceil(rownum)
              self.likeView.snp.remakeConstraints { (make) in
              make.top.equalTo(self.desWeb.snp.bottom)
              make.left.right.equalToSuperview()
              make.height.equalTo(rownum*260+52+20)
            }
        })
        likeView.callselBlock { (info) in
            let vc = M_ProductDetailVC(info: info)
            self.pushViewController(vc)
        }
        scrollView.bottomEqualTo(likeView, offset: 50)
        btmtoolView.drawLabel(label: wuhuoLab, text: "所选地区暂时无货，非常抱歉！", fontSize: 12, textColor: .xFC4C02) { (make) in
            make.height.equalTo(40)
            make.left.right.equalToSuperview()
            make.bottom.equalTo(btmtoolView.snp.top)
        }
        wuhuoLab.backgroundColor = .xFEE6DC
        wuhuoLab.textAlignment = .center
        wuhuoLab.isHidden = true
        
        ///底部工具条部分
        let btm = 50
        safeView.drawView(view: btmtoolView) { (make) in
            make.bottom.equalToSuperview().offset(btm)
            make.left.right.equalToSuperview()
            make.height.equalTo(100)
        }
        btmtoolView.backgroundColor = .white
        
        
        let kefuBtn = BtmTitleBtn()
        btmtoolView.drawButton(button: kefuBtn,imageNamed: "xiangqingkefu_82") { (make) in
            make.top.equalToSuperview().offset(8)
            make.left.equalToSuperview().offset(20)
        }
        kefuBtn.hitEdgInsets = .init(top: -20, left: -20, bottom: -20, right: -20)
        kefuBtn.btmLab.text = "客服"
        kefuBtn.addTarget(self, action: #selector(_kefuButtonClick(button:)), for: .touchUpInside)
        
        let carBtn = BtmTitleBtn()
        btmtoolView.drawButton(button: carBtn,imageNamed: "xiangqinggwuche_83") { (make) in
            make.top.equalToSuperview().offset(8)
            make.left.equalToSuperview().offset(74)
        }
        carBtn.hitEdgInsets = .init(top: -40, left: -30, bottom: -40, right: -30)
        carBtn.btmLab.text = "购物车"
        carBtn.addTarget(self, action: #selector(_gouwucheButtonClick(button:)), for: .touchUpInside)
        
        addBtn = btmtoolView.drawButton(title: "加入购物车", titleColor: .white, fontSize: 14) { (make) in
            make.left.equalToSuperview().offset(135)
            make.top.equalToSuperview().offset(7.5)
            make.height.equalTo(35)
            make.width.equalTo(110)
        }
        addBtn.backgroundColor = .xFFC000
        addBtn.layer.cornerRadius = 17.5
        addBtn.addTarget(self, action: #selector(_addButtonClick(button:)), for: .touchUpInside)
        
        buyBtn = btmtoolView.drawButton(title: "立即兑换", titleColor: .white, fontSize: 14) { (make) in
            make.right.equalToSuperview().offset(-10)
            make.top.equalToSuperview().offset(7.5)
            make.height.equalTo(35)
            make.width.equalTo(110)
        }
        buyBtn.backgroundColor = .xFC4C02
        buyBtn.layer.cornerRadius = 17.5
        buyBtn.addTarget(self, action: #selector(_buyButtonClick(button:)), for: .touchUpInside)
        
        safeView.drawButton(button: topBtn,imageNamed: "jiantou", { (make) in
            make.bottom.equalTo(btmtoolView.snp.top).offset(-15)
            make.right.equalToSuperview().offset(-15)
            make.width.height.equalTo(45)
        })
        topBtn.isHidden = true
        topBtn.backgroundColor = .white
        topBtn.layer.cornerRadius = 22.5
        topBtn.addTarget(self, action: #selector(_topButtonClick(button:)), for: .touchUpInside)
        
        //禁止长按,放缩
        var javascript = "document.documentElement.style.webkitTouchCallout='none';"//禁止长按
        javascript += "document.documentElement.style.webkitUserSelect='none';"//禁止选择
        var noneSelectScript = WKUserScript(source: javascript, injectionTime: WKUserScriptInjectionTime.atDocumentEnd, forMainFrameOnly: true)
        desWeb.configuration.userContentController.addUserScript(noneSelectScript)
        javascript = "var script = document.createElement('meta');script.name = 'viewport';script.content=\"width=device-width, user-scalable=no\";document.getElementsByTagName('head')[0].appendChild(script);"//禁止缩放
        noneSelectScript = WKUserScript(source: javascript, injectionTime: WKUserScriptInjectionTime.atDocumentEnd, forMainFrameOnly: false)
        desWeb.configuration.userContentController.addUserScript(noneSelectScript)
    }
    
    class BtmTitleBtn : Button {
        let btmLab = UILabel()
        
        override var isSelected: Bool {
            didSet{
                if isSelected {
                    btmLab.textColor = .xFC4C02
                    btmLab.text = "已收藏"
                }
                else {
                    btmLab.textColor = .x999999
                    btmLab.text = "收藏"
                }
            }
        }
        
        override func draw(_ rect: CGRect) {
            if let _ = btmLab.superview {
                return
            }
            self.addSubview(btmLab)
            self.clipsToBounds = false
            drawLabel(label: btmLab,text: btmLab.text, fontSize: 9, textColor: btmLab.textColor) { (make) in
                make.top.equalTo(self.snp.bottom).offset(3)
                make.centerX.equalToSuperview()
            }
            btmLab.isUserInteractionEnabled = false
            btmLab.textAlignment = .center
        }
    }
}

// MARK: event & action
extension M_ProductDetailVC {
//    @objc func headImgTap(tap:UITapGestureRecognizer){
//        browser.pageIndex = headImgCurPage
//        browser.show()
//    }
    
    @objc func jdADViewTap(tap:UITapGestureRecognizer){
        UIApplication.shared.keyWindow?.endEditing(true)
        let view = M_AddressSelView()
        safeView.drawView(view: view) { (make) in
            make.left.right.top.bottom.equalToSuperview()
        }
        view.backgroundColor = .init(white: 0, alpha: 0.5)
        view.callSelBlock(block: { (v) in
            
//            self.provinceCode = v.provinceCode.getString("provinceID") ?? ""
//            self.cityCode = v.cityCode.getString("cityID") ?? ""
//            self.districtCode = v.districtCode.getString("districtID") ?? ""
//            self.townCode = v.townCode.getString("townID") ?? ""
            
            var ad = v.provinceCode.getString("provinceName") ?? ""
            if ad.count == 0 {
                return
            }
            ad += " "
            ad += v.cityCode.getString("cityName") ?? ""
            ad += " "
            ad += v.districtCode.getString("districtName") ?? ""
            ad += " "
            ad += v.townCode.getString("townName") ?? ""
            self.localLab.text = ad
            
            self.getAddressIDByAddressName(provinceName: v.provinceCode.getString("provinceName") ?? "", cityName: v.cityCode.getString("cityName") ?? "", districtName: v.districtCode.getString("districtName") ?? "", townName: v.townCode.getString("townName") ?? "", callback: { (data) in
                self.getProductStock(productNo: self.productInfo.getString("productNo") ?? "", provinceCode: data.getString("provinceCode") ?? "", cityCode: data.getString("cityCode") ?? "", districtCode: data.getString("districtCode") ?? "", townCode: data.getString("townCode") ?? "", callback: { (data) in
                    let stockNum = data.getString("stockStatusCode") ?? ""
                    let havetext = stockNum == "109002" ? "有货 >" : "无货 >"
                    if stockNum == "109002" {
                        self.addBtn.backgroundColor = .xFFC000
                        self.addBtn.isEnabled = true
                        self.buyBtn.backgroundColor = .xFC4C02
                        self.buyBtn.isEnabled = true
                        self.wuhuoLab.isHidden = true
                    }
                    else {
                        self.addBtn.backgroundColor = .x999999
                        self.addBtn.isEnabled = false
                        self.buyBtn.backgroundColor = .x999999
                        self.buyBtn.isEnabled = false
                        self.wuhuoLab.isHidden = false
                    }
                    self.localLab.superview?.drawLabel(label: self.haveLab, text: havetext, fontSize: 15, textColor:.x333333) { (make) in
                        make.centerY.equalTo(self.localLab)
                        make.left.equalTo(self.localLab.snp.right).offset(5)
                    }
                })
                
            })
        })
    }
    
    @objc func _buyButtonClick(button:UIButton){
        var items = [OrderItem]()
        let item = OrderItem(fromDictionary: ["productNo": productInfo.getString("productNo") ?? "","productNum": 1])
        items.append(item)
        let orderData = OrderDataClass(fromDictionary: ["identityToken":LocalStorage.getString(forKey: USER_IDENTITYTOKEN) ?? "",
                                                        "orderDeliverModeCode":"",
                                                        "orderDeliverSiteCode":"",
                                                        "zoneCode": "105001",
                                                        "remark": "留言",
                                                        "items":items])
        let vc = M_OrderVC(orderData, info: [productInfo])
        pushViewController(vc)
    }
    
    @objc func _addButtonClick(button:UIButton){
        addCar(productNo: productInfo.getString("productNo") ?? "")
    }
    
    @objc func _carButtonClick(button:UIButton){
        let vc = M_CartListVC()
        vc.isshowBack = true
        pushViewController(vc)
    }
    
    @objc func _jichuClick(button:UIButton){
        let vc = UIViewController.topMostController() ?? self
        let pview = M_DetailJichuView()
        vc.view.drawView(view: pview, { (make) in
            make.left.right.bottom.top.equalToSuperview()
        })
        pview.backgroundColor = .clear
    }
    
    @objc func _favButtonClick(button:UIButton){
        if favBtn.isSelected {
            delfavAction(collectID: productInfo.getString("collectID") ?? "", callback: {
                self.favBtn.isSelected = false

                UIViewController.topMostController()?.view.makeToast("已取消收藏", duration: 2.0, position: .center)
            })
        }
        else {
            favAction(productNo: productInfo.getString("productNo") ?? "",zoneCode: productInfo.getString("zoneCode") ?? "", callback: {
                UIViewController.topMostController()?.view.makeToast("收藏成功", duration: 2.0, position: .center)

                self.favBtn.isSelected = true
                self.getIsFav(productNo: self.productInfo.getString("productNo") ?? "", callback: { (data) in
                    if data.getBool("isExist") ?? false,let collectID = data.getString("collectID") {
                        self.favBtn.isSelected = true
                        self.productInfo.updateValue(collectID, forKey: "collectID")
                    }
                })
            })
        }
    }
    
    @objc func _gouwucheButtonClick(button:UIButton){
        let vc = M_CartListVC()
        vc.isshowBack = true
        pushViewController(vc)
    }
    
    @objc func _kefuButtonClick(button:UIButton){
        let vc = M_SimpleArticleVC()
        pushViewController(vc)
        let qidiandic = LocalStorage.getDic(forKey: QIDIAN_KEY)
        vc.loadUrl(qidiandic?.getString("id") ?? "https://url.cn/50hfdES?_type=wpa&qidian=true")

        vc.headTitle.text = "联系客服"
    }
    
    @objc func _xiaoxiButtonClick(button: Button) {
        let vc = M_NewsListVC()
        pushViewController(vc)
    }
    
    @objc func _fenxiangButtonClick(button:UIButton){
        UMSocialUIManager.setPreDefinePlatforms([NSNumber.init(integerLiteral: UMSocialPlatformType.wechatTimeLine.rawValue), NSNumber.init(value: UMSocialPlatformType.wechatSession.rawValue)])
        UMSocialUIManager.addCustomPlatformWithoutFilted(UMSocialPlatformType(rawValue: 1001)!, withPlatformIcon: UIImage.init(named: "share_link2"), withPlatformName: "复制链接")
        UMSocialUIManager.showShareMenuViewInWindow { (platform: UMSocialPlatformType, userInfo: [AnyHashable : Any]?) in
            if platform == UMSocialPlatformType(rawValue: 1001)! {
                let pastboard = UIPasteboard.general
                pastboard.string = self.shareWebPageUrl

                let popup = PopupBox(infoText: "已复制")
                if let vc = UIViewController.topMostController() {
                    popup.show(vc: vc)
                }
                return
            }
            
            let messageObject = UMSocialMessageObject()
            let img =  SDImageCache.shared.imageFromCache(forKey:self.shareImageUrlString)
            let webMessageContent = UMShareWebpageObject.shareObject(withTitle: self.shareTitle, descr: self.shareContent, thumImage:img)
            webMessageContent?.webpageUrl = self.shareWebPageUrl

            messageObject.shareObject = webMessageContent
            UMSocialManager.default()?.share(to: platform, messageObject: messageObject, currentViewController: self, completion: { (info, error) in
                
            })
        }
    }
    
//    @objc func functickDown(){
//       var p = headImgScrView.contentOffset
//        p.x += 375
//        if p.x >= headImgScrView.contentSize.width {
//            p.x = 0
//        }
//        headImgScrView.setContentOffset(p, animated: true)
//    }
    
    @objc func _homeButtonClick(button:UIButton){
        let noT = NSNotification.Name(rawValue: GOTOHONME)
        let dic = ["selIndex":0]
        NotificationCenter.default.post(name: noT, object: nil, userInfo:dic)
        
        for vc in self.navigationController?.children ?? [] {
            if vc.isKind(of: MainTabBarController.self) {
//                self.timerinvalidate()
                self.headImageSlide.stopTimer()
                self.navigationController?.popToViewController(vc, animated: true)
            }
        }
    }
    
    @objc func _topButtonClick(button:Button){
        scrollView.setContentOffset(.zero, animated: true)
    }
    
    func updateWebViewHeight(_ height: CGFloat) {
        desWeb.snp.updateConstraints { (make) in
            make.height.equalTo(height)
        }
    }
    
    func addWebViewObserver() {
        observing = true
        desWeb.scrollView.addObserver(self, forKeyPath: "contentSize", options: .new, context: nil)
    }
    
    func removeWebViewObserver() {
        if observing {
            desWeb.scrollView.removeObserver(self, forKeyPath: "contentSize", context: nil)
            observing = false
        }
    }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        guard let keyPath = keyPath else {
            super.observeValue(forKeyPath: nil, of: object, change: change, context: context)
            return
        }
        if keyPath == "contentSize" {
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
                self.updateWebViewHeight(self.desWeb.scrollView.contentSize.height)
            }
        }
    }
        
    ///UIScrollViewDelegate
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
//        if scrollView.tag == 999 {
//            let page = scrollView.contentOffset.x/375
//            headImgCurPage = Int(page) + 1
//            curLab.text = anyToString(headImgCurPage)! + " /"
//        }
//        else
        if scrollView.tag == 888 {
            if scrollView.contentOffset.y > 0 {
                topBtn.isHidden = false
            }
            else {
                topBtn.isHidden = true
            }
        }
    }
    
    //MARK:-WKUIDelegate
    func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
        // 在JS端调用alert函数时，会触发此代理方法。
        // JS端调用alert时所传的数据可以通过message拿到
        // 在原生得到结果后，需要回调JS，是通过completionHandler回调
    }

    func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) {
        // JS端调用confirm函数时，会触发此方法
        // 通过message可以拿到JS端所传的数据
        // 在iOS端显示原生alert得到YES/NO后
        // 通过completionHandler回调给JS端
    }

    func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void) {
        // JS端调用prompt函数时，会触发此方法
        // 要求输入一段文本
        // 在原生输入得到文本内容后，通过completionHandler回调给JS
    }

    //MARK:-WKNavigationDelegate
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        //页面开始加载，可在这里给用户loading提示
    }

    func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
        //内容开始到达时
    }

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        //页面加载完成时
//        updateWebViewHeight(desWeb.scrollView.contentSize.height)
        if (!observing) { addWebViewObserver() }
    }

    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        //页面加载出错，可在这里给用户错误提示
    }

    func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) {
        //收到服务器重定向请求
    }

    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        // 在请求开始加载之前调用，决定是否跳转
        decisionHandler(WKNavigationActionPolicy.allow)
    }

    func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
        //在收到响应开始加载后，决定是否跳转
        decisionHandler(WKNavigationResponsePolicy.allow)
    }

    //MARK:-WKScriptMessageHandler
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        //h5给端传值的内容，可在这里实现h5与原生的交互时间
        let messageDic = message.body
        print(messageDic)

    }

    ///AMapSearchDelegate,MAMapViewDelegate
    //逆地理编码
        func reGeoCoding(location: CLLocation) {
            let req = AMapReGeocodeSearchRequest()
            let coordinate = location.coordinate
//            logDebug(coordinate)
            req.location = AMapGeoPoint.location(withLatitude: CGFloat(coordinate.latitude) ,
                                                     longitude: CGFloat(coordinate.longitude))
            search?.aMapReGoecodeSearch(req)
            search?.delegate = self
        }
        
         //搜索请求发起后的回调
        //失败
        func aMapSearchRequest(_ request: Any!, didFailWithError error: Error!) {
    //        showAlert(content: "温馨提示", title: "无法获取当前地址:\(String(describing: error))")
            
//            logDebug("无法获取当前地址:\(String(describing: error))") //可能光是全名也不合适
//
//            localLab.text = "无法获取当前位置"
//            mapView.delegate = nil
        }
        
        //成功
        func onReGeocodeSearchDone(_ request: AMapReGeocodeSearchRequest!, response: AMapReGeocodeSearchResponse!) {
            if isLocationed {
                return
            }
            logDebug(response.regeocode?.formattedAddress) //可能光是全名也不合适
            localLab.text = response.regeocode.addressComponent.province + " " +
                response.regeocode.addressComponent.city + " " +
                response.regeocode.addressComponent.district + " "
            localLab.text! += response.regeocode.addressComponent.township
            mapView.delegate = nil
            getAddressIDByAddressName(provinceName: response.regeocode.addressComponent.province, cityName: response.regeocode.addressComponent.city, districtName: response.regeocode.addressComponent.district, townName: response.regeocode.addressComponent.township, callback: { (data) in
                //定位成功
                self.isLocationed = true
                
                self.getProductStock(productNo: self.productInfo.getString("productNo") ?? "", provinceCode: data.getString("provinceCode") ?? "", cityCode: data.getString("cityCode") ?? "", districtCode: data.getString("districtCode") ?? "", townCode: data.getString("townCode") ?? "", callback: { (data) in
                    let stockNum = data.getString("stockStatusCode") ?? ""
                    let havetext = stockNum == "109002" ? "有货 >" : "无货 >"
                    if stockNum == "109002" {
                        self.addBtn.backgroundColor = .xFFC000
                        self.addBtn.isEnabled = true
                        self.buyBtn.backgroundColor = .xFC4C02
                        self.buyBtn.isEnabled = true
                        self.wuhuoLab.isHidden = true
                    }
                    else {
                        self.addBtn.backgroundColor = .x999999
                        self.addBtn.isEnabled = false
                        self.buyBtn.backgroundColor = .x999999
                        self.buyBtn.isEnabled = false
                        self.wuhuoLab.isHidden = false
                    }
                    self.localLab.superview?.drawLabel(label: self.haveLab, text: havetext, fontSize: 15, textColor:.x333333) { (make) in
                        make.centerY.equalTo(self.localLab)
                        make.left.equalTo(self.localLab.snp.right).offset(5)
                    }
                })
            })
        }
        
        //mapViewh回调
        func mapView(_ mapView: MAMapView!, didUpdate userLocation: MAUserLocation!, updatingLocation: Bool) {
//            master.lat = anyToString(userLocation.location.coordinate.latitude) ?? ""
//            master.lng = anyToString(userLocation.location.coordinate.longitude) ?? ""
//            if anyToDouble(curLocation?.coordinate.latitude) == anyToDouble(userLocation.location.coordinate.latitude),
//                anyToDouble(curLocation?.coordinate.longitude) == anyToDouble(userLocation.location.coordinate.longitude)  {
//                return
//            }
//            print(anyToString(userLocation.location.coordinate.latitude) ?? "")
//            print(anyToString(userLocation.location.coordinate.longitude) ?? "")
            if let curLocation = userLocation.location {
                reGeoCoding(location: curLocation)
            }
        }
        
        func mapView(_ mapView: MAMapView!, didFailToLocateUserWithError error: Error!) {
        }
        
        func mapViewDidFailLoadingMap(_ mapView: MAMapView!, withError error: Error!) {
        }
}


class M_ProductJINGDONGBox : UIView {
    init(){
        super.init(frame: .init(x: 0, y: 0, width: 75, height: 23.5))
        let roundCornerBox = UIView(frame: .init(x: 0, y: 0, width: 75*2, height: 23.5*2))
        roundCornerBox.backgroundColor = .xFC4C02
        roundCornerBox.layer.cornerRadius = 4
        self.addSubview(roundCornerBox)
        self.clipsToBounds = true
        self.drawLabel(text: "京东配送", fontSize: 15,fontWeight: .medium ,  textColor: .white) { (make) in
            make.centerX.centerY.equalToSuperview()
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override var intrinsicContentSize: CGSize {
        return CGSize(width: 75, height: 23.5)
    }
}


class M_ProductDetailHeadImageSlide : SlideshowImageView<[String:Any?]> {
    var imageUrlPrefix : String = ""
    let curLab : UILabel
    
    //图片浏览器
    let browser = JXPhotoBrowser()
    
    //协议部分
    //从数据中获取url
    override func getImageUrl(data:[String:Any?])->String?{
        if let urlString = data.getString("imgUrl") {
            if urlString == "zanwu" {
                return nil
            }
            return (imageUrlPrefix+urlString).addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
        }
        return nil
    }
    //向image设置url
    override func setImage(image:UIImageView,url:String?){
        if url == nil {
            image.image = UIImage(named: "zanwu")
            return
        }
        if SDImageCache.shared.imageFromCache(forKey:url!) == nil {
            let urlimg = URL(string: url!)
            let downloader = SDWebImageDownloader.shared
            downloader.downloadImage(with: urlimg, options: [], progress: nil, completed: { (image,data,error,sec) in
                SDImageCache.shared.store(image, forKey: url!, completion: nil)
            })
        }
        let urlObject = URL(string: url!)
        image.sd_setImage(with:urlObject)
    }
    //更新页面的时候触发
    override func onUpdatePosition(cursor:Int,count:Int){
//        print(cursor,count)
        curLab.text = anyToString(cursor+1)! + " /"
    }
    
    override func onCenterImageTap(data: [String : Any?]) {
        browser.pageIndex = list.cursor
        browser.show()
    }
    
    init(curLab : UILabel) {
        self.curLab = curLab
        super.init(cornerRadius: 0, insetSize: 0, defaultList: [["imgUrl":"zanwu"]], imageMode: .scaleAspectFit)
        browser.numberOfItems = { [weak self] in
            return self?.list.list.count ?? 0
        }
        browser.reloadCellAtIndex = {[weak self] context in
            guard let list = self?.list.list,list.count > 0 else {
                return
            }
            let browserCell = context.cell as? JXPhotoBrowserImageCell
            let indexPath = IndexPath(item: context.index, section: 0)
            
            if let urlstring = self?.getImageUrl(data: list[indexPath.item]) {
                browserCell?.imageView.image = SDImageCache.shared.imageFromCache(forKey:urlstring)
            }
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

